package com.threeox.commonlibrary.entity.base;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.alibaba.fastjson.JSON;
import com.threeox.commonlibrary.entity.engine.model.base.BaseModelMsg;

/**
 *
 * @ClassName: BaseObj
 *
 * @Description: TODO(基类的对象)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2016/12/19 下午9:00
 *
 * @version 1.0
 */
public class BaseObj implements Cloneable, Serializable {

	protected final String TAG = this.getClass().getSimpleName();

	/**
	 * 转换为JSON字符串
	 * 
	 * @return
	 */
	public String toJSON() {
		return JSON.toJSONString(this);
	}

	/**
	 * 转换为JSON对象
	 * 
	 * @param text
	 * @return
	 */
	public <T extends Object> T fromJson(String text) {
		return (T) JSON.parseObject(text, this.getClass());
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

    /**
     * 复制一个新的对象
     *
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public <T extends BaseObj> T copyObject() throws IOException, ClassNotFoundException {
        // 将该对象序列化成流,因为写在流里的是对象的一个拷贝，而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);
        // 将流序列化成对象
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (T) ois.readObject();
    }
}
